using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections.ObjectModel;
using System.Windows.Forms.Design;
using Sipek.Common;
using Sipek.Common.CallControl;

#if LINUX
#else
using WaveLib.AudioMixer; // see http://www.codeproject.com/KB/graphics/AudioLib.aspx
#endif

using System.Data.Odbc;

namespace Sipek
{
    public partial class frmMain : Form
    {
        private Timer tmr = new Timer();  // Refresh Call List
        private SipekResources _resources = null;
        private EUserStatus _lastUserStatus = EUserStatus.AVAILABLE;
        private string HEADER_TEXT;
        public static string startTime;
        //private byte strID = 0;
        //private bool mAvoidEvents = false;
        public const string DB_CONN_STRING = "DSN=kubikcrm";
        private string sql;


        private SipekResources SipekResources
        {
            get { return _resources; }
        }

        public bool IsInitialized
        {
            get { return SipekResources.StackProxy.IsInitialized; }
        }

        private void ConnectToData()
        {
            System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection();
            //conn.ConnectionString = "DSN=kubikcrm";
            conn.ConnectionString = DB_CONN_STRING;
            try
            {
                conn.Open();
            }
            catch (Exception)
            {
                MessageBox.Show("Failed To Connect");
            }
            finally
            {
                conn.Close();
            }
            //sql = "SELECT id,customer_name,pic,pic_pos,pic2,pic2_pos,eMIAl,tlp,city FROM customers WHERE customer_name<>'' AND type='Corporate' AND rev='SAM' ORDER BY id ASC LIMIT 1000;";
            //FillListView(conn, sql, lvData);
            sql = "SELECT DATE_FORMAT(activity_date,'%d-%m-%Y'),TIME_FORMAT(activity_time,'%h:%i:%s'),activity_type,activity_contact,customer_name,activity_desc,tlp FROM activity_transaction INNER JOIN customers ON customers.id=activity_transaction.customer_id INNER JOIN activity ON activity.id=activity_transaction.activity_id WHERE activity_transaction.pic='SRL' AND activity_transaction.customer_id=" + lvDataCust.SelectedItems[0].Text + " ORDER BY activity_date DESC,activity_time DESC ";
            FillListView(conn, sql, listView1);
        }

        private void FillListView(OdbcConnection conn, String sql, ListView lv)
        {
            lv.Items.Clear();
            OdbcCommand cmdRead;
            OdbcDataReader datReader;
            string strField;
            strField = sql;
            cmdRead = new OdbcCommand(strField, conn);
            try
            {
                conn.Open();
                datReader = cmdRead.ExecuteReader();
                // fill ListView
                while (datReader.Read())
                {
                    ListViewItem objListItem = new ListViewItem(datReader.GetValue(0).ToString());
                    for (int c = 1; c < datReader.FieldCount; c++)
                    {
                        objListItem.SubItems.Add(datReader.GetValue(c).ToString());
                    }
                    objListItem.ImageIndex = 5;
                    lv.Items.Add(objListItem);
                }
                datReader.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("Failed To Connect Table ! ");
            }
            finally
            {

                conn.Close();
            }

        }

        private void CRUD(String sSQLCommand)
        {
            System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection();
            //conn.ConnectionString = "DSN=kubikcrm";
            conn.ConnectionString = "DSN=kubikcrm";
            OdbcCommand cmdAdder = new OdbcCommand(sSQLCommand, conn);
            cmdAdder.Connection.Open(); // Create the command object
            cmdAdder.ExecuteNonQuery(); // Execute the SQL command
        }

        private void UpdateCallLines(int sessionId)
        {
            listViewCallLines.Items.Clear();

            try
            {
                // get entire call list
                Dictionary<int, IStateMachine> callList = SipekResources.CallManager.CallList;

                foreach (KeyValuePair<int, IStateMachine> kvp in callList)
                {
                    string number = kvp.Value.CallingNumber;
                    string name = kvp.Value.CallingName;

                    string duration = kvp.Value.Duration.ToString();
                    if (duration.IndexOf('.') > 0) duration = duration.Remove(duration.IndexOf('.')); // remove miliseconds
                    // show name & number or just number
                    string display = name.Length > 0 ? name + " / " + number : number;
                    string stateName = kvp.Value.StateId.ToString();
                    String stateCustomer = lvDataCust.SelectedItems[0].SubItems[2].Text;
                    if (SipekResources.CallManager.Is3Pty) stateName = "CONFERENCE";
                    ListViewItem lvi = new ListViewItem(new string[] {
            stateName, display, duration,stateCustomer});

                    lvi.Tag = kvp.Value;
                    listViewCallLines.Items.Add(lvi);
                    lvi.Selected = true;

                    // display info
                    //toolStripStatusLabel1.Text = item.Value.lastInfoMessage;
                    DateTime DD = DateTime.Now;
                    Properties.Settings.Default.CustomerStartDate = String.Format("{0:yyyy-MM-dd}", DD);
                    Properties.Settings.Default.CustomerStartTime = String.Format("{0:HH:mm:ss}", DD);
                    //startTime = Properties.Settings.Default.CustomerStartTime;
                    //MessageBox.Show(Properties.Settings.Default.CustomerStartTime); 
                    //strID = strID;
                    if (lvi.Text == "ACTIVE")
                    {
                        //MessageBox.Show("Active");
                        //sql = "INSERT INTO activity_transaction(activity_date,date_stamp,activity_time,customer_id,pic,user_stamp)VALUES('" + Properties.Settings.Default.CustomerStartDate + "','" + Properties.Settings.Default.CustomerStartDate + "','" + Properties.Settings.Default.CustomerStartTime + "'," + Properties.Settings.Default.CustomerID + ",'" + Properties.Settings.Default.CustomerRev + "','" + Properties.Settings.Default.CustomerRev + "');";
                        //sql = "INSERT INTO activity_transaction(activity_date
                        //MessageBox.Show(sql);
                        //CRUD(sql);
                    }
                    else if (lvi.Text == "RELEASED")
                    {
                        Properties.Settings.Default.CustomerID = lvDataCust.SelectedItems[0].SubItems[0].Text;
                        Properties.Settings.Default.CustomerName = lvDataCust.SelectedItems[0].SubItems[1].Text;
                        Properties.Settings.Default.CustomerPic = lvDataCust.SelectedItems[0].SubItems[2].Text;
                        Properties.Settings.Default.CustomerTlp = lvDataCust.SelectedItems[0].SubItems[7].Text;    
                        frmCallLog myNewForm = new frmCallLog();
                        myNewForm.ShowDialog();
                    }
                }

                if (callList.Count > 0)
                {
                    // control refresh timer
                    tmr.Start();

                    // Remember last status
                    if (toolStripComboBoxUserStatus.SelectedIndex != (int)EUserStatus.OTP)
                        _lastUserStatus = (EUserStatus)toolStripComboBoxUserStatus.SelectedIndex;

                    // Set user status "On the Phone"
                    toolStripComboBoxUserStatus.SelectedIndex = (int)EUserStatus.OTP;
                }
                else
                {
                    toolStripComboBoxUserStatus.SelectedIndex = (int)_lastUserStatus;
                    //MessageBox.Show("t");
                }

            }
            //catch (Exception e)
            catch (SystemException)
            {
                // TODO!!!!!!!!!!! Sychronize SHARED RESOURCES!!!!
            }
            //listViewCallLines.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);

            // close balloon tip
            notifyIcon.Visible = false;
            notifyIcon.Visible = true;
        }

        private void UpdateCallRegister()
        {
            lock (this)
            {
                listViewCallRegister.Items.Clear();
                // Update Dial field
                toolStripComboDial.Items.Clear();

                Stack<CCallRecord> results = SipekResources.CallLogger.getList();

                int cnt = 0; int dialedcnt = 0;
                foreach (CCallRecord item in results)
                {
                    string duration = item.Duration.ToString();
                    if (duration.IndexOf('.') > 0) duration = duration.Remove(duration.IndexOf('.')); // remove miliseconds

                    string recorditem = item.Number;
                    CBuddyRecord rec = null;
                    int buddyId = CBuddyList.getInstance().getBuddyId(item.Number);
                    if (buddyId > -1)
                    {
                        string name = "";
                        rec = CBuddyList.getInstance()[buddyId];
                        name = rec.FirstName + " " + rec.LastName;
                        name = name.Trim();
                        recorditem = name + ", " + item.Number;
                    }
                    else if (item.Name.Length > 0)
                    {
                        recorditem = item.Name + ", " + item.Number;
                    }

                    ListViewItem lvi = new ListViewItem(new string[] {
               item.Type.ToString(), recorditem.Trim(), item.Time.ToString(), duration});

                    lvi.Tag = item;

                    listViewCallRegister.Items.Insert(cnt, lvi);

                    // add item to dial combo (if dialed)
                    if (item.Type == ECallType.EDialed)
                    {
                        toolStripComboDial.Items.Insert(dialedcnt++, item.Number);
                    }
                    // increase counter
                    cnt++;
                }
            }
        }

        private void UpdateAccountList()
        {
            listViewAccounts.Items.Clear();

            for (int i = 0; i < SipekResources.Configurator.Accounts.Count; i++)
            {
                IAccount acc = SipekResources.Configurator.Accounts[i];
                string name;

                if (acc.AccountName.Length == 0)
                {
                    name = "--empty--";
                }
                else
                {
                    name = acc.AccountName;
                }
                // create listviewitem
                ListViewItem item = new ListViewItem(new string[] { name, acc.RegState.ToString() });
                // mark default account
                if (i == SipekResources.Configurator.DefaultAccountIndex)
                {
                    // Mark default account; todo!!! Coloring!
                    item.BackColor = Color.LightGray;

                    string label = "";
                    // check registration status
                    if (acc.RegState == 200)
                    {
                        this.Text = HEADER_TEXT + " - " + acc.AccountName + " (" + acc.DisplayName + ")"; ;
                        label = "Registered" + " - " + acc.AccountName + " (" + acc.DisplayName + ")";
                    }
                    else if (acc.RegState == 0)
                    {
                        label = "Trying..." + " - " + acc.AccountName;
                    }
                    else
                    {
                        label = "Not registered" + " - " + acc.AccountName;
                    }
                    toolStripStatusLabel.Text = label;
                    txtUsername.Text = acc.AccountName;
                }
                else
                {
                }

                listViewAccounts.Items.Add(item);

            }
        }


        private void RefreshForm()
        {
            if (IsInitialized)
            {
                // Update Call Status
                UpdateCallLines(-1);

                // Update Call Register
                UpdateCallRegister();

                // Update Buddy List
                //UpdateBuddyList();

                // Update account list
                UpdateAccountList();
                //ConnectToData();
            }

            // Refresh toolstripbuttons
            toolStripButtonDND.Checked = SipekResources.Configurator.DNDFlag;
            toolStripButtonAA.Checked = SipekResources.Configurator.AAFlag;

            unconditionalToolStripMenuItem.Checked = SipekResources.Configurator.CFUFlag;
            toolStripTextBoxCFUNumber.Text = SipekResources.Configurator.CFUNumber;

            noReplyToolStripMenuItem.Checked = SipekResources.Configurator.CFNRFlag;
            toolStripTextBoxCFNRNumber.Text = SipekResources.Configurator.CFNRNumber;

            busyToolStripMenuItem.Checked = SipekResources.Configurator.CFBFlag;
            toolStripTextBoxCFBNumber.Text = SipekResources.Configurator.CFBNumber;

            // check if user status available
            toolStripComboBoxUserStatus.Enabled = SipekResources.Configurator.PublishEnabled;
        }

        //////////////////////////////////////////////////////////////////////////////////////
        /// Register callbacks and synchronize threads
        /// 
        delegate void DRefreshForm();
        delegate void DCallStateChanged(int sessionId);
        delegate void MessageReceivedDelegate(string from, string message);
        delegate void BuddyStateChangedDelegate(int buddyId, int status, string text);
        delegate void DMessageWaiting(int mwi, string text);
        delegate void DIncomingCall(int sessionId, string number, string info);

        void CallManager_IncomingCallNotification(int sessionId, string number, string info)
        {
            if (InvokeRequired)
                this.BeginInvoke(new DIncomingCall(this.OnIncomingCall), new object[] { sessionId, number, info });
            else
                OnIncomingCall(sessionId, number, info);
        }

        private void OnIncomingCall(int sessionId, string number, string info)
        {
            notifyIcon.ShowBalloonTip(30, "Sugeng Communicator", "Telepon Masuk Dari " + number + "!", ToolTipIcon.Info);
        }

        private void mMixer_MixerLineChanged(Mixer mixer, MixerLine line)
        {
            //mAvoidEvents = true;

            try
            {
                float balance = -1;
                MixerLine frontEndLine = (MixerLine)trackBar1.Tag;
                if (frontEndLine == line)
                {
                    int volume = 0;
                    if (line.Channels != 2)
                        volume = line.Volume;
                    else
                    {
                        line.Channel = Channel.Left;
                        int left = line.Volume;
                        line.Channel = Channel.Right;
                        int right = line.Volume;
                        if (left > right)
                        {
                            volume = left;
                            // TIP: Do not reset the balance if both left and right channel have 0 value
                            if (left != 0 && right != 0)
                                balance = (volume > 0) ? -(1 - (right / (float)left)) : 0;
                        }
                        else
                        {
                            volume = right;
                            // TIP: Do not reset the balance if both left and right channel have 0 value
                            if (left != 0 && right != 0)
                                balance = (volume > 0) ? 1 - (left / (float)right) : 0;
                        }
                    }

                    if (volume >= 0)
                        trackBar1.Value = volume;

                }

                // adjust toolstrip checkboxes
                if ((MixerLine)toolStripMicMuteButton.Tag == line)
                {
                    toolStripMicMuteButton.Checked = line.Volume == 0 ? true : false;
                }
                else if ((MixerLine)toolStripMuteButton.Tag == line)
                {
                    toolStripMuteButton.Checked = line.Mute;
                }
            }
            finally
            {
                //mAvoidEvents = false;
            }
        }

        private Mixers mMixers;
        private int _lastMicVol = 0;

        private void LoadAudioValues()
        {
            try
            {
                mMixers = new Mixers();
            }
            catch (Exception e)
            {
                ///report error
                (new ErrorDialog("Initialize Error " + e.Message, "Audio Mixer cannot initialize! \r\nCheck audio configuration and start again!")).ShowDialog();
                return;
            }
            // set callback
            mMixers.Playback.MixerLineChanged += new WaveLib.AudioMixer.Mixer.MixerLineChangeHandler(mMixer_MixerLineChanged);
            mMixers.Recording.MixerLineChanged += new WaveLib.AudioMixer.Mixer.MixerLineChangeHandler(mMixer_MixerLineChanged);

            MixerLine pbline = mMixers.Playback.UserLines.GetMixerFirstLineByComponentType(MIXERLINE_COMPONENTTYPE.SRC_WAVEOUT);

            trackBar1.Tag = pbline;
            toolStripMuteButton.Tag = pbline;
            MixerLine recline = mMixers.Recording.UserLines.GetMixerFirstLineByComponentType(MIXERLINE_COMPONENTTYPE.SRC_MICROPHONE); ;
            toolStripMicMuteButton.Tag = recline;

            //If it is 2 channels then ask both and set the volume to the bigger but keep relation between them (Balance)
            int volume = 0;
            float balance = 0;
            if (pbline.Channels != 2)
                volume = pbline.Volume;
            else
            {
                pbline.Channel = Channel.Left;
                int left = pbline.Volume;
                pbline.Channel = Channel.Right;
                int right = pbline.Volume;
                if (left > right)
                {
                    volume = left;
                    balance = (volume > 0) ? -(1 - (right / (float)left)) : 0;
                }
                else
                {
                    volume = right;
                    balance = (volume > 0) ? (1 - (left / (float)right)) : 0;
                }
            }

            if (volume >= 0)
                this.trackBar1.Value = 6;
            else
                this.trackBar1.Enabled = false;

            // toolstrip checkboxes
            this.toolStripMuteButton.Checked = pbline.Mute;
            this.toolStripMicMuteButton.Checked = recline.Volume == 0 ? true : false;
            _lastMicVol = recline.Volume;
        }

        public void onCallStateChanged(int sessionId)
        {
            if (InvokeRequired)
            {
                this.BeginInvoke(new DRefreshForm(this.RefreshForm));
                notifyIcon.ShowBalloonTip(290, "Sugeng Communicator", "Telepon Keluar " + "!", ToolTipIcon.Info);
                //MessageBox.Show("Awal");
                //input data Exceute
            }
            else
            {
                //MessageBox.Show("Akhir");
                RefreshForm();
            }

        }
        private void MessageReceived(string from, string message)
        {
            // extract buddy ID
            //string buddyId = parseFrom(from);

            // check if ChatForm already opened
            foreach (Form ctrl in Application.OpenForms)
            {
                if (ctrl.Name == "ChatForm")
                {
                    //((ChatForm)ctrl).BuddyName = buddyId;
                    //((ChatForm)ctrl).LastMessage = message;
                    //ctrl.Focus();
                    //return;
                }
            }

            // if not, create new instance
            ChatForm bf = new ChatForm(SipekResources);
            //int id = CBuddyList.getInstance().getBuddyId(buddyId);
            //if (id >= 0)
            //{
            //_buddyId = id;        
            //  CBuddyRecord buddy = CBuddyList.getInstance()[id];
            //_titleText.Caption = buddy.FirstName + ", " + buddy.LastName;
            //  bf.BuddyId = (int)id;
            //}
            // bf.BuddyName = buddyId;
            //bf.LastMessage = message;
            //bf.ShowDialog();
        }

        public void onMessageReceived(string from, string message)
        {
            if (InvokeRequired)
                this.BeginInvoke(new MessageReceivedDelegate(this.MessageReceived), new object[] { from, message });
            else
                MessageReceived(from, message);
        }

        public void onAccountStateChanged(int accId, int accState)
        {
            if (InvokeRequired)
                this.BeginInvoke(new DRefreshForm(this.RefreshForm));
            else
                RefreshForm();
        }

        public void onMessageWaitingIndication(int mwi, string text)
        {
            if (InvokeRequired)
                this.BeginInvoke(new DMessageWaiting(this.MessageWaiting), new object[] { mwi, text });
            else
                MessageWaiting(mwi, text);
        }

        private void MessageWaiting(int mwi, string info)
        {
            // "Messages-Waiting: yes\r\nMessage-Account: sip:*97@192.168.60.211\r\nVoice-Message: 5/2 (0/0)\r\n"
            // extract values 
            string[] parts = info.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            string vmaccount = "";
            string noofvms = "";

            if (parts.Length == 3)
            {
                int index = parts[1].IndexOf("Message-Account: ");
                if (index == 0)
                {
                    vmaccount = parts[1].Substring("Message-Account: ".Length);
                }

                if (parts[2].IndexOf("Voice-Message: ") >= 0)
                {
                    noofvms = parts[2].Substring("Voice-Message: ".Length);
                }

            }

            if (mwi > 0)
                toolStripStatusLabelMessages.Text = "Message Waiting: " + noofvms + " - Account: " + vmaccount;
            else
                toolStripStatusLabelMessages.Text = "No Messages!";

        }

        public void UpdateCallTimeout(object sender, EventArgs e)
        {
            if (listViewCallLines.Items.Count == 0) return;

            for (int i = 0; i < listViewCallLines.Items.Count; i++)
            {
                ListViewItem item = listViewCallLines.Items[i];
                IStateMachine sm = (IStateMachine)item.Tag;
                if (sm.IsNull) continue;

                string duration = sm.RuntimeDuration.ToString();
                if (duration.IndexOf('.') > 0) duration = duration.Remove(duration.IndexOf('.')); // remove miliseconds
                item.SubItems[2].Text = duration;
                //item.SubItems[2].Text = "Mangap";
                //item.SubItems[3].Text = duration;
            }
            // restart timer
            if (listViewCallLines.Items.Count > 0)
            {
                tmr.Start();

            }

        }

        public frmMain()
        {
            InitializeComponent();
#if TLS
                  this.Text += " TLS";
                  HEADER_TEXT = this.Text;
#else
            HEADER_TEXT = this.Text;
#endif
            // Check if settings upgrade needed?
            if (Properties.Settings.Default.cfgUpdgradeSettings == true)
            {
                Properties.Settings.Default.Upgrade();
                Properties.Settings.Default.cfgUpdgradeSettings = false;
            }
            // Create resource object containing SipekSdk and other Sipek related data
            _resources = new SipekResources(this);
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            LoadAudioValues();
            //MessageBox.Show(Convert.ToString(listViewAccounts.Items[0].));
            // Register callbacks from callcontrol
            SipekResources.CallManager.CallStateRefresh += onCallStateChanged;
            SipekResources.CallManager.IncomingCallNotification += new DIncomingCallNotification(CallManager_IncomingCallNotification);
            // Register callbacks from pjsipWrapper
            //SipekFactory.getCommonProxy().CallStateChanged += onTelephonyRefresh;
            SipekResources.Messenger.MessageReceived += onMessageReceived;
            //SipekResources.Messenger.BuddyStatusChanged += onBuddyStateChanged;
            SipekResources.Registrar.AccountStateChanged += onAccountStateChanged;
            SipekResources.StackProxy.MessageWaitingIndication += onMessageWaitingIndication;

            // Initialize and set factory for CallManager

            int status = SipekResources.CallManager.Initialize();
            SipekResources.CallManager.CallLogger = SipekResources.CallLogger;

            if (status != 0)
            {
                (new ErrorDialog("Initialize Error", "Init SIP stack problem! \r\nPlease, check configuration and start again! \r\nStatus code " + status)).ShowDialog();
                return;
            }

            // initialize Stack
            SipekResources.Registrar.registerAccounts();

            // Initialize BuddyList
            CBuddyList.getInstance().Messenger = SipekResources.Messenger;
            CBuddyList.getInstance().initialize();

            //////////////////////////////////////////////////////////////////////////
            // load settings

            this.UpdateCallRegister();

            // Buddy list
            //this.UpdateBuddyList();

            this.UpdateAccountList();

            // Set user status
            toolStripComboBoxUserStatus.SelectedIndex = (int)EUserStatus.AVAILABLE;

            // scoh::::03.04.2008:::pjsip ISSUE??? At startup codeclist is different as later 
            // set codecs priority...
            // initialize/reset codecs - enable PCMU and PCMA only
            int noOfCodecs = SipekResources.StackProxy.getNoOfCodecs();
            for (int i = 0; i < noOfCodecs; i++)
            {
                string codecname = SipekResources.StackProxy.getCodec(i);
                if (SipekResources.Configurator.CodecList.Contains(codecname))
                {
                    // leave default
                    SipekResources.StackProxy.setCodecPriority(codecname, 128);
                }
                else
                {
                    // disable
                    SipekResources.StackProxy.setCodecPriority(codecname, 0);
                }
            }

            // timer 
            tmr.Interval = 1000;
            tmr.Tick += new EventHandler(UpdateCallTimeout);
        }

        private void tbAccount_Click(object sender, EventArgs e)
        {
            (new SettingsForm(this.SipekResources)).ShowDialog();
            RefreshForm();
        }

        private void listViewAccounts_DoubleClick(object sender, EventArgs e)
        {
            SettingsForm sf = new SettingsForm(this.SipekResources);
            //sf.activateTab("");
            sf.ShowDialog();
        }

        private void toolStripButtonCall_Click(object sender, EventArgs e)
        {
            // TODO check if incoming call!!!
            if (listViewCallLines.SelectedItems.Count > 0)
            {
                ListViewItem lvi = listViewCallLines.SelectedItems[0];
                CStateMachine call = (CStateMachine)lvi.Tag;
                if (call.Incoming)
                {
                    SipekResources.CallManager.onUserAnswer(call.Session);
                    return;
                }
            }
            if (toolStripComboDial.Text.Length > 0)
            {
                SipekResources.CallManager.createOutboundCall(toolStripComboDial.Text);
            }
        }

        private void toolStripButtonRelease_Click(object sender, EventArgs e)
        {
            if (listViewCallLines.SelectedItems.Count > 0)
            {
                ListViewItem lvi = listViewCallLines.SelectedItems[0];
                SipekResources.CallManager.onUserRelease(((CStateMachine)lvi.Tag).Session);
            }
        }

        private void toolStripButtonHoldRetrieve_Click(object sender, EventArgs e)
        {
            if (listViewCallLines.SelectedItems.Count > 0)
            {
                ListViewItem lvi = listViewCallLines.SelectedItems[0];

                SipekResources.CallManager.onUserHoldRetrieve(((CStateMachine)lvi.Tag).Session);
            }
        }

        private void toolStrip3PtyButton_Click(object sender, EventArgs e)
        {
            if (listViewCallLines.SelectedItems.Count > 0)
            {
                ListViewItem lvi = listViewCallLines.SelectedItems[0];
                // TODO implement 3Pty
                SipekResources.CallManager.onUserConference(((CStateMachine)lvi.Tag).Session);
            }
        }

        private void listViewCallRegister_DoubleClick(object sender, EventArgs e)
        {
            if (listViewCallRegister.SelectedItems.Count > 0)
            {
                ListViewItem lvi = listViewCallRegister.SelectedItems[0];
                CCallRecord record = (CCallRecord)lvi.Tag;
                SipekResources.CallManager.createOutboundCall(record.Number);
            }
        }

        private void toolStripTextBoxTransferTo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 0x0d)
            {
                if (listViewCallLines.SelectedItems.Count > 0)
                {
                    ListViewItem lvi = listViewCallLines.SelectedItems[0];
                    if (toolStripTextBoxTransferTo.Text.Length > 0)
                    {
                        SipekResources.CallManager.onUserTransfer(((CStateMachine)lvi.Tag).Session, toolStripTextBoxTransferTo.Text);
                    }
                }
                contextMenuStripCalls.Close();
            }
        }
        private void attendedTransferToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listViewCallLines.SelectedItems.Count > 0)
            {
                ListViewItem lvi = listViewCallLines.SelectedItems[0];
                CStateMachine call = (CStateMachine)lvi.Tag;
                // check call states
                if (SipekResources.CallManager.Count >= 2)
                {
                    //get ACTIVE call
                    //List<IStateMachine> activeCalls = SipekResources.CallManager[EStateId.ACTIVE];
                    //if (activeCalls.Count == 0) return;

                    // get HOLDING call
                    //List<IStateMachine> holdingCalls = SipekResources.CallManager[EStateId.HOLDING];
                    //if (holdingCalls.Count == 0) return;

                    // transfer ACTIVE to HOLDING
                    //SipekResources.CallManager.OnUserTransferAttendant(activeCalls[0].Session, holdingCalls[0].Session);
                }
            }
        }

        private void contextMenuStripCalls_Opening(object sender, CancelEventArgs e)
        {
            // Hide all items...
            foreach (ToolStripMenuItem mi in contextMenuStripCalls.Items)
            {
                mi.Visible = false;
            }

            if (listViewCallLines.SelectedItems.Count > 0)
            {
                ListViewItem lvi = listViewCallLines.SelectedItems[0];

                if (SipekResources.CallManager.Count <= 0)
                {
                    return;
                }
                else
                {
                    EStateId stateId = ((CStateMachine)lvi.Tag).StateId;
                    switch (stateId)
                    {
                        case EStateId.INCOMING:
                            acceptToolStripMenuItem.Visible = true;
                            transferToolStripMenuItem.Visible = true;
                            break;
                        case EStateId.ACTIVE:
                            holdRetrieveToolStripMenuItem.Text = "Hold";
                            holdRetrieveToolStripMenuItem.Visible = true;
                            transferToolStripMenuItem.Visible = true;
                            //sendMessageToolStripMenuItem.Visible = true;
                            attendedTransferToolStripMenuItem.Visible = true;
                            break;
                        case EStateId.HOLDING:
                            holdRetrieveToolStripMenuItem.Text = "Retrieve";
                            holdRetrieveToolStripMenuItem.Visible = true;
                            break;
                    }

                }
                // call
                releaseToolStripMenuItem.Visible = true;
            }
        }


   

        //* Region Button Dial *//
        private void btnDial1_Click(object sender, EventArgs e)
        {
            cbDial.Text = cbDial.Text + "1";
        }

        private void btnDial2_Click(object sender, EventArgs e)
        {
            cbDial.Text = cbDial.Text + "2";
        }

        void ClearCustomer()
        {
            Properties.Settings.Default.CustomerID = "";
            Properties.Settings.Default.CustomerName = "";
            Properties.Settings.Default.CustomerPic = "";
            Properties.Settings.Default.CustomerStartDate = "";
            //Properties.Settings.Default.CustomerStartTime = "";
            Properties.Settings.Default.CustomerTlp = "";
            Properties.Settings.Default.CustomerRev = "";
        }

        private void btnHangup_Click(object sender, EventArgs e)
        {
            cbDial.Text = "";
            lvDataCust.Enabled = true;
            if (listViewCallLines.SelectedItems.Count > 0)
            {
                ClearCustomer();
                ListViewItem lvi = listViewCallLines.SelectedItems[0];
                SipekResources.CallManager.onUserRelease(((CStateMachine)lvi.Tag).Session);
                Properties.Settings.Default.CustomerID = lvDataCust.SelectedItems[0].SubItems[0].Text;
                Properties.Settings.Default.CustomerName = lvDataCust.SelectedItems[0].SubItems[1].Text;
                Properties.Settings.Default.CustomerPic = lvDataCust.SelectedItems[0].SubItems[2].Text;
                Properties.Settings.Default.CustomerTlp = lvDataCust.SelectedItems[0].SubItems[7].Text;
                frmCallLog myNewForm = new frmCallLog();
                myNewForm.ShowDialog();
                
            }

        }

        private void btnDial3_Click(object sender, EventArgs e)
        {
            cbDial.Text = cbDial.Text + "3";
        }

        private void btnDial4_Click(object sender, EventArgs e)
        {
            cbDial.Text = cbDial.Text + "4";
        }

        private void btnDial5_Click(object sender, EventArgs e)
        {
            cbDial.Text = cbDial.Text + "5";
        }

        private void btnDial6_Click(object sender, EventArgs e)
        {
            cbDial.Text = cbDial.Text + "6";
        }

        private void btnDial7_Click(object sender, EventArgs e)
        {
            cbDial.Text = cbDial.Text + "7";
        }

        private void btnDial8_Click(object sender, EventArgs e)
        {
            cbDial.Text = cbDial.Text + "8";
        }

        private void btnDial9_Click(object sender, EventArgs e)
        {
            cbDial.Text = cbDial.Text + "9";
        }

        private void btnDialStart_Click(object sender, EventArgs e)
        {
            cbDial.Text = cbDial.Text + "*";
        }

        private void btnDial0_Click(object sender, EventArgs e)
        {
            cbDial.Text = cbDial.Text + "0";
        }

        private void btnDialHash_Click(object sender, EventArgs e)
        {
            cbDial.Text = cbDial.Text + "#";
        }

        private void Dial(string DialNumber)
        {
            // TODO check if incoming call!!!
            
            if (listViewCallLines.SelectedItems.Count > 0)
            {
                ListViewItem lvi = listViewCallLines.SelectedItems[0];
                CStateMachine call = (CStateMachine)lvi.Tag;
                if (call.Incoming)
                {
                    SipekResources.CallManager.onUserAnswer(call.Session);
                    return;
                }
            }
            if (DialNumber.Length > 0)
            {
                //DateTime DD = DateTime.Now;
                //Properties.Settings.Default.CustomerStartDate = String.Format("{0:yyyy-MM-dd}", DD);
                //Properties.Settings.Default.CustomerStartTime =   String.Format("{0:HH:mm:ss}", DD);   
                SipekResources.CallManager.createOutboundCall(DialNumber);
            }
        }

        private void btnDial_Click(object sender, EventArgs e)
        {

            //MessageBox.Show(Properties.Settings.Default.CustomerStartTime);
            Dial(cbDial.Text);
        }

        //* End Region Button Dial *//

    

        private void toolStripKeyboardButton_Click(object sender, EventArgs e)
        {
            frmCallLog myNewForm = new frmCallLog();
            myNewForm.Show();
        }

        
   

        private void btnSearchCustomer_Click(object sender, EventArgs e)
        {
            cbDial.Enabled = true;
            btnRefresh.Visible = true;
            System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection();
            //conn.ConnectionString = "DSN=kubikcrm";
            conn.ConnectionString = DB_CONN_STRING;
            try
            {
                conn.Open();
            }
            catch (Exception)
            {
                MessageBox.Show("Failed To Connect");
            }
            finally
            {
                conn.Close();
            }
            sql = "SELECT id,customer_name,pic,pic_pos,pic2,pic2_pos,email,tlp,city FROM customers WHERE customer_name<>''  AND rev2='SRL' AND latest_activity<>4 AND latest_activity<>2 AND customer_name LIKE '%" + txtSearchCustName.Text + "%' ORDER BY id ASC LIMIT 100;";
            FillListView(conn, sql, lvDataCust);
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            txtSearchCustName.Text = "";
            ConnectToData();
        }

        private void lvData_Click(object sender, EventArgs e)
        {
            ConnectToData();
            lblCustomerName.Text = lvDataCust.SelectedItems[0].SubItems[1].Text;
        }

      

        private void btnSearchCust_Click(object sender, EventArgs e)
        {
            cbDial.Enabled = true;
            btnRefresh.Visible = true;
            System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection();
            conn.ConnectionString = "DSN=kubikcrm";
            //conn.ConnectionString = DB_CONN_STRING;
            try
            {
                conn.Open();
            }
            catch (Exception)
            {
                MessageBox.Show("Failed To Connect1");
            }
            finally
            {
                conn.Close();
            }
            sql = "SELECT id,customer_name,pic,pic_pos,pic2,pic2_pos,email,tlp,city FROM customers WHERE customer_name<>'' AND rev2='SRL' AND latest_activity<>4 AND latest_activity<>2 AND customer_name LIKE '%" + txtSearchCustName.Text + "%'  ORDER BY id ASC LIMIT 100;";
            FillListView(conn, sql, lvDataCust);
        }

        private void lvDataCust_Click(object sender, EventArgs e)
        {
            ConnectToData();
            lblCustomerName.Text = lvDataCust.SelectedItems[0].SubItems[1].Text;
        }

        private void lvDataCust_DoubleClick(object sender, EventArgs e)
        {
            cbDial.Text = lvDataCust.SelectedItems[0].SubItems[7].Text;
            Properties.Settings.Default.CustomerID = lvDataCust.SelectedItems[0].SubItems[0].Text;
            Properties.Settings.Default.CustomerName = lvDataCust.SelectedItems[0].SubItems[1].Text;
            Properties.Settings.Default.CustomerPic = lvDataCust.SelectedItems[0].SubItems[2].Text;
            Properties.Settings.Default.CustomerTlp = lvDataCust.SelectedItems[0].SubItems[7].Text;
            lblNo.Text = lvDataCust.SelectedItems[0].SubItems[1].Text;
            lvDataCust.Enabled = false;
            btnDial.Focus();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection();
            conn.ConnectionString = "DSN=kubikcrm";
            //conn.ConnectionString = DB_CONN_STRING;
            try
            {
                conn.Open();
            }
            catch (Exception)
            {
                MessageBox.Show("Failed To Connect");
            }
            finally
            {
                conn.Close();
            }
            sql = "SELECT TIME_FORMAT(activity_time,'%h:%i:%s'),TIME_FORMAT(activity_time2,'%h:%i:%s'),timediff(activity_time,activity_time2),activity_type,activity_contact,customer_name,activity_desc,tlp FROM activity_transaction INNER JOIN customers ON customers.id=activity_transaction.customer_id INNER JOIN activity ON activity.id=activity_transaction.activity_id WHERE activity_transaction.pic='SRL' AND activity_date = CURDATE() ORDER BY activity_date DESC,activity_time DESC ";
            //MessageBox.Show(sql);
            FillListView(conn, sql,listView2);

        }

        private void button1_Click(object sender, EventArgs e)
        {
            System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection();
            conn.ConnectionString = "DSN=kubikcrm";
            //conn.ConnectionString = DB_CONN_STRING;
            try
            {
                conn.Open();
            }
            catch (Exception)
            {
                MessageBox.Show("Failed To Connect");
            }
            finally
            {
                conn.Close();
            }
            sql = "SELECT DATE_FORMAT(activity_date,'%d/%m/%Y'),TIME_FORMAT(activity_time,'%h:%i:%s'),TIME_FORMAT(activity_time2,'%h:%i:%s'),timediff(activity_time,activity_time2),activity_type,activity_contact,customer_name,activity_desc,tlp FROM activity_transaction INNER JOIN customers ON customers.id=activity_transaction.customer_id INNER JOIN activity ON activity.id=activity_transaction.activity_id WHERE activity_transaction.pic='SRL' AND WEEK(activity_date)=WEEK(CURDATE()) ORDER BY activity_date DESC,activity_time DESC ";
            FillListView(conn, sql, listView3);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection();
            conn.ConnectionString = "DSN=kubikcrm";
            //conn.ConnectionString = DB_CONN_STRING;
            try
            {
                conn.Open();
            }
            catch (Exception)
            {
                MessageBox.Show("Failed To Connect");
            }
            finally
            {
                conn.Close();
            }
            sql = "SELECT DATE_FORMAT(activity_date,'%d/%m/%Y'),TIME_FORMAT(activity_time,'%h:%i:%s'),TIME_FORMAT(activity_time2,'%h:%i:%s'),timediff(activity_time,activity_time2),activity_type,activity_contact,customer_name,activity_desc,tlp FROM activity_transaction LEFT JOIN customers ON customers.id=activity_transaction.customer_id JOIN activity ON activity.id=activity_transaction.activity_id WHERE activity_transaction.pic='SRL' AND MONTH(activity_date)=MONTH(CURDATE()) ORDER BY activity_date DESC,activity_time DESC ";
            FillListView(conn, sql, listView4);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection();
            conn.ConnectionString = "DSN=kubikcrm";
            //conn.ConnectionString = DB_CONN_STRING;
            try
            {
                conn.Open();
            }
            catch (Exception)
            {
                MessageBox.Show("Failed To Connect");
            }
            finally
            {
                conn.Close();
            }
            sql = "SELECT DATE_FORMAT(activity_date,'%d/%m/%Y'),TIME_FORMAT(activity_time,'%h:%i:%s'),TIME_FORMAT(activity_time2,'%h:%i:%s'),timediff(activity_time,activity_time2),activity_type,activity_contact,customer_name,activity_desc,tlp FROM activity_transaction INNER JOIN customers ON customers.id=activity_transaction.customer_id INNER JOIN activity ON activity.id=activity_transaction.activity_id WHERE activity_transaction.pic='SRL' AND MONTH(activity_date)>=MONTH(CURDATE()) AND MONTH(activity_date)<=MONTH(CURDATE())+ 3 ORDER BY activity_date DESC,activity_time DESC ";
            FillListView(conn, sql, listView5);
        }

        

        
    }
}
